package com.hks.quart.controller;

import java.util.List;

import javax.annotation.Resource;

import com.hks.quart.utils.HttpResult;
import com.hks.quart.utils.HttpStatus;
import org.quartz.CronExpression;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hks.quart.entity.ScheduleJobBean;
import com.hks.quart.entity.ScheduleJobLogBean;
import com.hks.quart.service.ScheduleJobLogService;
import com.hks.quart.service.ScheduleJobService;
import com.hks.quart.utils.ScheduleUtil;

import io.swagger.annotations.ApiOperation;

/**
 * @author zhanglq
 * @version 1.0
 * @date 2021/9/1 11:38
 * @info 定时任务控制器
 */
@RestController
@RequestMapping("/Quart")
public class ScheduleJobController {

    @Autowired
    private ScheduleJobService scheduleJobService;

    @Autowired
    private ScheduleJobLogService jobLogService;

    @Resource
    private Scheduler scheduler;

    @RequestMapping("/list")
    @ApiOperation("获取定时器列表")
    public HttpResult list(@RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size, @RequestBody ScheduleJobBean scheduleJob) {
        QueryWrapper<ScheduleJobBean> queryWrapper = new QueryWrapper<>(scheduleJob);
        Page<ScheduleJobBean> page = this.scheduleJobService.page(new Page<>(current, size), queryWrapper);
        return HttpResult.create(HttpStatus.SUCCESS, page);
    }

    /**
     * 添加定时器
     */
    @RequestMapping("/insertJob")
    public HttpResult insertJob(@RequestBody ScheduleJobBean scheduleJobBean) {
        //        ScheduleJobBean scheduleJobBean = new ScheduleJobBean() ;
        //        scheduleJobBean.setJobId(1L);
        //        scheduleJobBean.setBeanName("getTimeTask");
        //        scheduleJobBean.setBeanName("selectForOracleToMysql");
        // 每分钟执行一次
        //        scheduleJobBean.setCronExpression("0 30 4 * * ?");
        //        scheduleJobBean.setParams("资金流水定期执行");
        //        scheduleJobBean.setStatus(0);
        //        scheduleJobBean.setRemark("资金流水");
        //        scheduleJobBean.setCreateTime(new Date());
        //        scheduleJobService.insert(scheduleJobBean) ;
        if (CronExpression.isValidExpression(scheduleJobBean.getCronExpression())) { //校验cron的表达式是否符合quart要求
            this.scheduleJobService.saveOrUpdate(scheduleJobBean);
            return HttpResult.create(HttpStatus.SUCCESS, scheduleJobBean);
        } else {
            return HttpResult.create(HttpStatus.FAIL, "cronExpression执行频率不符合规则，请检查！");
        }
    }

    /**
     * 执行一次定时器
     */
    @RequestMapping("/runJob")
    public HttpResult runJob(@RequestBody ScheduleJobBean jobBean) {
        if (jobBean.getJobId() != null) {
            this.scheduleJobService.run(jobBean.getJobId());
            return HttpResult.create(HttpStatus.SUCCESS);
        }
        return HttpResult.create(HttpStatus.FAIL);
    }

    /**
     * 更新定时器
     */
    @RequestMapping("/updateJob")
    public HttpResult updateJob(@RequestBody ScheduleJobBean jobBean) {
        try {
            scheduleJobService.updateByPrimaryKeySelective(jobBean);
            return HttpResult.create(HttpStatus.SUCCESS);
        } catch (Exception e) {
            return HttpResult.create(HttpStatus.FAIL,"更新定时任务失败！请联系管理员");
        }
    }

    /**
     * 停止定时器
     */
    @RequestMapping("/pauseJob")
    public HttpResult pauseJob(@RequestBody ScheduleJobBean jobBean) {
        try {
            scheduleJobService.pauseJob(jobBean.getJobId());
            return HttpResult.create(HttpStatus.SUCCESS);
        } catch (Exception e) {
            return HttpResult.create(HttpStatus.FAIL,"停止定时任务失败！请联系管理员");
        }
    }

    /**
     * 恢复定时器
     */
    @RequestMapping("/resumeJob")
    public HttpResult resumeJob(@RequestBody ScheduleJobBean jobBean) {
        try {
            scheduleJobService.resumeJob(jobBean.getJobId());
            return HttpResult.create(HttpStatus.SUCCESS);
        } catch (Exception e) {
            return HttpResult.create(HttpStatus.FAIL,"恢复定时任务失败！请联系管理员");
        }
    }

    /**
     * 删除定时器
     */
    @RequestMapping("/deleteJob")
    public HttpResult deleteJob(@RequestBody List<ScheduleJobBean> ids) {
        try {
            //        scheduleJobService.delete(jobId);
            ids.forEach((ScheduleJobBean id) -> ScheduleUtil.deleteJob(scheduler, id.getJobId()));
            this.scheduleJobService.removeByIds(ids);
            return HttpResult.create(HttpStatus.SUCCESS);
        } catch (Exception e) {
            return HttpResult.create(HttpStatus.FAIL,"删除定时任务失败！请联系管理员");
        }
    }
    /**
     * 更新启用定时任务
     */
    @RequestMapping("/updateTimer")
    public HttpResult updateTimer(@RequestParam(value = "id")Long id) {
        try {
            this.scheduleJobService.updateTimer(id);
            return HttpResult.create(HttpStatus.SUCCESS);
        } catch (Exception e) {
            return HttpResult.create(HttpStatus.FAIL,"更新启用定时任务失败！请联系管理员",e.getMessage());
        }
    }
    /**
     * 删除定时器日志
     */
    @RequestMapping("/deleteJobLog")
    public HttpResult deleteJobLog(@RequestBody List<ScheduleJobLogBean> jobLogBeans) {
        jobLogBeans.forEach((ScheduleJobLogBean id) -> this.jobLogService.removeById(id));
        return HttpResult.create(HttpStatus.SUCCESS);
    }

    @RequestMapping("/getJobLog")
    @ApiOperation("获取定时器日志列表")
    public HttpResult getJobLog(@RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size, @RequestBody ScheduleJobLogBean jobLogBean) {
        QueryWrapper<ScheduleJobLogBean> queryWrapper = new QueryWrapper<>(jobLogBean);
        queryWrapper.orderByDesc("create_time");
        Page<ScheduleJobLogBean> page = this.jobLogService.page(new Page<>(current, size), queryWrapper);
        return HttpResult.create(HttpStatus.SUCCESS, page);
    }

}
